package net.sinodata.smartframework.component;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Description: Spring上下文类 用于获取Spring容器中的Bean
 * 
 * @author: yinliangyun
 * @date: 2021-5-18
 */
@Component
public class SpringContext implements ApplicationContextAware {
	
	private static ApplicationContext applicationContext;

	/* (non-Javadoc)
	 * <p>Title: setApplicationContext</p>
	 * <p>Description: </p>
	 * @param applicationContext
	 * @throws BeansException
	 * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
	 */
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringContext.applicationContext = applicationContext;
	}
	
	/**
	 * 获取applicationContext
	 * 
	 * @return
	 */
    public static ApplicationContext getApplicationContext() {
    	return applicationContext;
    }

    /**
     * 通过name获取Bean
     * 
     * @param name
     * @return
     */
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    /**
     * 通过class获取Bean
     * 
     * @param <T>
     * @param clazz
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    /**
     * 通过name以及Clazz返回指定的Bean
     * 
     * @param <T>
     * @param name
     * @param clazz
     * @return
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
    
    /**
     * 获取application.yml中active 的值
     * 
     * @return
     */
    public static String getActiveProfile() {
    	return applicationContext.getEnvironment().getActiveProfiles()[0];
    }


	public static boolean containsBean(String name) {
		return applicationContext.containsBean(name);
	}

	public static boolean isSingleton(String name) {
		return applicationContext.isSingleton(name);
	}

	public static Class<? extends Object> getType(String name) {
		return applicationContext.getType(name);
	}

}
